﻿using System;
using System.Web;
using System.Web.Mvc;

namespace BadmintonBuddy.Helpers
{
    public static class CaptchaHelper
    {
        private const string ImgFormat = "<img src=\"{0}\" />"
                            + @"<input type=""hidden"" id=""solution"" value=""{1}"" />";

        public static MvcHtmlString Captcha(this HtmlHelper html, string name)
        {
            
            string solution = MakeRandomSolution();            

            // Render an <IMG> tag for the distorted text,
            // plus a hidden field to contain the challenge GUID
            var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
            string url = urlHelper.Action("Render",  new { solution });
            string htmlToDisplay = string.Format(ImgFormat, url, solution);
            return MvcHtmlString.Create(htmlToDisplay);
        }

        private static string MakeRandomSolution()
        {
            Random rng = new Random();
            int length = rng.Next(5, 7);
            char[] buf = new char[length];
            for (int i = 0; i < length; i++)
                buf[i] = (char)('a' + rng.Next(26));
            return new string(buf);
        }
    }

}